package com.shunde.xunjian.service.impl;


import com.google.gson.Gson;
import com.shunde.xunjian.entity.ruoyi.SysUser;
import com.shunde.xunjian.entity.ruoyi.UserInfo;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.concurrent.TimeUnit;

@Service
public class RedisServiceImpl {

    private final RedisTemplate<String, String> redisTemplate;


    public RedisServiceImpl(RedisTemplate<String, String> redisTemplate) {
        this.redisTemplate = redisTemplate;
        System.out.println("redis已连接");
    }

    /**
     * 删除指定key
     * @param key
     * @return
     */
    public boolean delKey(String key) {
        return redisTemplate.delete(key);
    }

    /**
     * 判断token是否存在
     * @param key
     * @return
     */
    public boolean hasKey(String key) {
        return redisTemplate.hasKey(key);
    }

    /**
     * 获取redis值
     *
     * @param key
     * @return
     */
    public Object getValue(String key) {
        return redisTemplate.opsForValue().get(key);
    }


    /**
     * 设置redis值
     *
     * @param key
     * @param value
     * @param seconds
     */
    public void setKeyWithExpire(String key, String value, long seconds) {
        redisTemplate.opsForValue().set(key, value, seconds, TimeUnit.SECONDS);
    }

    /**
     * 获取当前用户对象
     * @param request
     * @return
     */
    public UserInfo getSysUser(HttpServletRequest request) {
        String token = request.getHeader("Authorization");
        String UserStr = getValue(token).toString();
        UserInfo user = new Gson().fromJson(UserStr, UserInfo.class);
        return user;
    }
}
